package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParam;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;


    @Override
    public PageResult search(RequestParam params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            //直接调用方法
            buildBasicQuery(params,request);

           SearchResponse response = client.search(request,RequestOptions.DEFAULT);
           return handleResponse(response);

        } catch (IOException e) {
            e.printStackTrace();
            //出现异常打印出来
            log.error("执行搜索功能出现异常，异常的原因是{}",e.getMessage());
        }
        return null;
    }


    //基础构建查询
    public void buildBasicQuery(RequestParam params,SearchRequest request){

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        String key = params.getKey();
        //key不为空
        if (StringUtils.isNoneBlank(key)) {
           boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
      //判断城市
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        //term查询品牌
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        //term查询星级
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName",params.getStarName()));
        }
        if (params.getMinPrince()!=null && params.getMaxPrince()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrince()).lte(params.getMaxPrince()));
        }

        //设置分页
        Integer page = params.getPage();
        Integer pageSize = params.getSize();
        request.source().from((page-1)*pageSize).size(pageSize);


        //查询位置
        if (StringUtils.isNotBlank(params.getLocation())) {
            request.source().
                    sort(SortBuilders.geoDistanceSort("location"
                    ,new GeoPoint(params.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
                    );
        }


        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(3)
                        )
                }
        );
        request.source().query(functionScoreQueryBuilder);






    }



    //出街结果的方法
    public PageResult handleResponse(SearchResponse response){
        //处理返回响应
        SearchHits hits = response.getHits();
        //得到总数total
        long total = hits.getTotalHits().value;
        SearchHit[] docAll = hits.getHits();
        //创建HotelDoc的集合
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit doc : docAll) {
            String jsonStr = doc.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(jsonStr, HotelDoc.class);
            Object[] sortValues = doc.getSortValues();
            if (sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            list.add(hotelDoc);
        }
       return new PageResult(total,list);
    }
}
